package com.bwda.dsrs.filecenter.service.impl;

import com.bwda.dsrs.base.centerbase.response.CentreListResponse;
import com.bwda.dsrs.base.centerbase.response.ResponseEntity;
import com.bwda.dsrs.base.util.CopyUtil;
import com.bwda.dsrs.filecenter.api.OrgServiceApi;
import com.bwda.dsrs.filecenter.api.clientappversion.datadict.DatadictCreateForm;
import com.bwda.dsrs.filecenter.api.clientappversion.datadict.DatadictQueryForm;
import com.bwda.dsrs.filecenter.api.clientappversion.datadict.DatadictVo;
import com.bwda.dsrs.filecenter.domain.BusinessConstants;
import com.bwda.dsrs.filecenter.domain.api.DatadictUpdateForm;
import com.bwda.dsrs.filecenter.domain.form.uploadsetting.UploadSettingForm;
import com.bwda.dsrs.filecenter.domain.vo.uploadsetting.UploadSettingCheckVo;
import com.bwda.dsrs.filecenter.domain.vo.uploadsetting.UploadSettingVo;
import com.bwda.dsrs.filecenter.service.UploadSetttingService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 上传限制管理
 *
 * @author liangjianyong
 * @date 2019/5/17
 */
@Service
public class UploadSettingServiceImpl implements UploadSetttingService {

    private final Logger logger = LoggerFactory.getLogger(UploadSettingServiceImpl.class);

    @Resource
    private OrgServiceApi orgServiceApi;

    @Override
    public UploadSettingVo query() {
        //查询上传的所有配置
        List<DatadictVo> results = queryUploadSetting();
        UploadSettingVo uploadSettingVo = new UploadSettingVo();
        //字典数据填充vo
        fillProperties(results, uploadSettingVo);
        return uploadSettingVo;
    }

    /**
     * 更新配置
     *
     * @param uploadSettingForm
     */
    @Override
    public void update(UploadSettingForm uploadSettingForm) {
        //查询上传的所有配置
        List<DatadictVo> results = queryUploadSetting();
        Map<String, DatadictVo> datadictVoMap = new HashMap<>(10);
        if (results != null) {
            datadictVoMap = results.stream().collect(Collectors.toMap(data -> data.getDataDictCode(), data -> data));
        }
        //最大上传大小
        if (datadictVoMap.containsKey(BusinessConstants.UploadSetting.FILE_MAX_UPLOAD_SIZE)) {
            //更新
            DatadictVo vo = datadictVoMap.get(BusinessConstants.UploadSetting.FILE_MAX_UPLOAD_SIZE);
            DatadictUpdateForm datadictUpdateForm = CopyUtil.transfer(vo, DatadictUpdateForm.class);
            datadictUpdateForm.setDataDictValue(String.valueOf(uploadSettingForm.getFileMaxUploadSize()));
            datadictUpdateForm.setOrderNum(1L);
            orgServiceApi.updateDatadict(datadictUpdateForm);
        } else {
            //新增
            DatadictCreateForm datadictCreateForm = fillDatadict(BusinessConstants.UploadSetting.FILE_MAX_UPLOAD_SIZE, String.valueOf(uploadSettingForm.getFileMaxUploadSize()));
            datadictCreateForm.setOrderNum(1L);
            datadictCreateForm.setDataDictValue(String.valueOf(uploadSettingForm.getFileMaxUploadSize()));
            orgServiceApi.addDatadict(datadictCreateForm);
        }

        //支持类型
        if (datadictVoMap.containsKey(BusinessConstants.UploadSetting.SUPPORT_UPLOAD_TYPE)) {
            //更新
            DatadictVo vo = datadictVoMap.get(BusinessConstants.UploadSetting.SUPPORT_UPLOAD_TYPE);
            if (StringUtils.isBlank(uploadSettingForm.getSupportUploadType())) {
                uploadSettingForm.setSupportUploadType(BusinessConstants.UPLOAD_NO_LIMIT_STR);
            }
            DatadictUpdateForm datadictUpdateForm = CopyUtil.transfer(vo, DatadictUpdateForm.class);
            datadictUpdateForm.setDataDictValue(uploadSettingForm.getSupportUploadType());
            datadictUpdateForm.setOrderNum(2L);
            orgServiceApi.updateDatadict(datadictUpdateForm);
        } else {
            //新增
            if (StringUtils.isBlank(uploadSettingForm.getSupportUploadType())) {
                uploadSettingForm.setSupportUploadType(BusinessConstants.UPLOAD_NO_LIMIT_STR);
            }
            DatadictCreateForm datadictCreateForm = fillDatadict(BusinessConstants.UploadSetting.SUPPORT_UPLOAD_TYPE, uploadSettingForm.getSupportUploadType());
            datadictCreateForm.setDataDictValue(uploadSettingForm.getSupportUploadType());
            datadictCreateForm.setOrderNum(2L);
            orgServiceApi.addDatadict(datadictCreateForm);
        }
        //备注
        if (datadictVoMap.containsKey(BusinessConstants.UploadSetting.REMARK)) {
            //更新
            DatadictVo vo = datadictVoMap.get(BusinessConstants.UploadSetting.REMARK);
            DatadictUpdateForm datadictUpdateForm = CopyUtil.transfer(vo, DatadictUpdateForm.class);
            if (StringUtils.isBlank(uploadSettingForm.getRemark())) {
                uploadSettingForm.setRemark(BusinessConstants.BLANK_ONE_STR);
            }
            datadictUpdateForm.setDataDictValue(uploadSettingForm.getRemark());
            datadictUpdateForm.setOrderNum(3L);
            orgServiceApi.updateDatadict(datadictUpdateForm);
        } else {
            //新增
            DatadictCreateForm datadictCreateForm = fillDatadict(BusinessConstants.UploadSetting.REMARK, uploadSettingForm.getRemark());
            if (StringUtils.isBlank(uploadSettingForm.getRemark())) {
                uploadSettingForm.setRemark(BusinessConstants.BLANK_ONE_STR);
            }
            datadictCreateForm.setDataDictValue(uploadSettingForm.getRemark());
            datadictCreateForm.setOrderNum(3L);
            orgServiceApi.addDatadict(datadictCreateForm);
        }
    }

    /**
     * 上传检查
     *
     * @param fileType
     * @param size     KB
     * @return
     */
    @Override
    public UploadSettingCheckVo checkUpload(String fileType, Integer size) {
        UploadSettingVo vo = this.query();
        if (size < 0) {
            return new UploadSettingCheckVo(false, "文件大小不合法");
        }
        //类型配置为空默认不限制文件类型
        if (StringUtils.isNotBlank(vo.getSupportUploadType())) {
            String[] supprtTypeArr = vo.getSupportUploadType().split(BusinessConstants.OnlineEditRightDescript.DESCRIPT_STR_SPLIT);
            List<String> supportTypeList = new ArrayList<>();
            Collections.addAll(supportTypeList, supprtTypeArr);
            if (fileType == null) {
                fileType = BusinessConstants.BLANK_STR;
            }
            if (supportTypeList != null && supportTypeList.size() > 0 && !supportTypeList.contains(fileType)) {
                return new UploadSettingCheckVo(false, "暂不支持此格式文件上传");
            }
        }
        if (vo.getFileMaxUploadSize() != null && vo.getFileMaxUploadSize() > 0 && vo.getFileMaxUploadSize() * BusinessConstants.MB2KB_SIZE < size) {
//            return new UploadSettingCheckVo(false, "文件过大");
        }
        return new UploadSettingCheckVo(true, "");
    }

    /**
     * 查询上传配置参数
     *
     * @return
     */
    private List<DatadictVo> queryUploadSetting() {
        //SystemServiceApi
        DatadictQueryForm queryForm = new DatadictQueryForm();
        queryForm.setDataDictTypeCode(BusinessConstants.UploadSetting.TYPE_CODE);
        try {
            ResponseEntity<CentreListResponse<DatadictVo>> responseEntity = orgServiceApi.queryDatadictFullList(queryForm);
            if (responseEntity.getData() == null || responseEntity.getData().getDataList() == null || responseEntity.getData().getDataList().size() == 0) {
                return null;
            }
            return responseEntity.getData().getDataList();
        } catch (Exception e) {
            logger.error("查询上传配置发生异常：{}", e);
        }
        return new ArrayList<DatadictVo>();
    }


    /**
     * 数据字典列表填充上传配置
     *
     * @param datadictVoList
     * @param uploadSettingVo
     */
    private void fillProperties(List<DatadictVo> datadictVoList, UploadSettingVo uploadSettingVo) {
        for (DatadictVo vo : datadictVoList) {
            if (vo.getDataDictCode() == null || vo.getDataDictValue() == null) {
                continue;
            } else if (BusinessConstants.UploadSetting.SYSTEM_NAME.equals(vo.getDataDictCode())) {
                //系统名称
                uploadSettingVo.setSystemName(vo.getDataDictValue());
            } else if (BusinessConstants.UploadSetting.FILE_MAX_UPLOAD_SIZE.equals(vo.getDataDictCode())) {
                //单个文件最大上传大小
                uploadSettingVo.setFileMaxUploadSize(Long.valueOf(vo.getDataDictValue()));
            } else if (BusinessConstants.UploadSetting.SUPPORT_UPLOAD_TYPE.equals(vo.getDataDictCode())) {
                //支持上传的文件类型
                uploadSettingVo.setSupportUploadType(vo.getDataDictValue());
                //解决oracle空字符
                if (BusinessConstants.UPLOAD_NO_LIMIT_STR.equals(vo.getDataDictValue())) {
                    uploadSettingVo.setSupportUploadType(BusinessConstants.BLANK_ONE_STR);
                }
            } else if (BusinessConstants.UploadSetting.REMARK.equals(vo.getDataDictCode())) {
                //备注
                uploadSettingVo.setRemark(vo.getDataDictValue());
            }
        }
    }

    /**
     * 填充字典（新增）
     */
    private DatadictCreateForm fillDatadict(String datadictCode, String datadictValue) {
        DatadictCreateForm createForm = new DatadictCreateForm();
        createForm.setDataDictTypeCode(BusinessConstants.UploadSetting.TYPE_CODE);
        createForm.setDataDictName(datadictCode);
        createForm.setDataDictCode(datadictCode);
        createForm.setDataDictValue(datadictValue);
        createForm.setStatus(BusinessConstants.StateType.ENABLE);
        return createForm;
    }

}
